'use strict';

const BaseController = require('./base');

class HouseController extends BaseController {
  get _service() {
    return 'house';
  }

  // 修改状态
  async _editStatus(status) {
    const { ctx } = this;
    const { id } = ctx.params();
    const result = await this._getService().update({ status, id });
    if (result) {
      this.success();
    } else {
      this.error('更新民宿信息失败');
    }
  }

  async create() {
    const { ctx } = this;
    const { name, address, rent, lon, lat, areaId, description } = ctx.params();
    const house = await this._getService().create({
      name,
      address,
      rent,
      lon,
      lat,
      areaId,
      oid: ctx.userId,
      description,
      status: 1,
    });
    const houseInfo = await ctx.service.houseInfo.create({ houseId: house.id, status: 1 });
    if (houseInfo) {
      this.success();
    } else {
      this.error('创建民宿失败');
    }
  }

  // 更新基本数据
  async update() {
    const { ctx } = this;
    const { name, address, rent, lon, lat, areaId, description } = ctx.params();
    const { id } = ctx.params;
    const result = await this._getService().update({ name, address, rent, lon, lat, areaId, description, status: 1, id });
    if (result) {
      this.success();
    } else {
      this.error('更新民宿失败');
    }
  }

  async agree() {
    await this._editStatus(3);
  }

  async disagree() {
    await this._editStatus(2);
  }

  async grounding() {
    await this._editStatus(4);
  }

  async undercarriage() {
    await this._editStatus(3);
  }

  async destroy() {
    const { ctx } = this;
    const { id } = ctx.params;
    const result = await this._getService().destory(+id);
    await this.service.houseInfo.destory(+id);
    if (result) {
      this.success();
    } else {
      this.error('删除民宿失败');
    }
  }

  async show() {
    await this._show('获取民宿失败');
  }

  async showShops() {
    const { ctx } = this;
    const { id } = ctx.params;
    const result = await this._getService().findOne({ id: +id, houseStatus: '4,5', houseInfoStatus: 3 });
    let device = {},
      advantage = {};
    if (result && result.houseInfo && result.houseInfo.advantageIds) {
      advantage = await this.service.advantage.findAll({ ids: result.houseInfo.advantageIds });
    }
    if (result && result.houseInfo && result.houseInfo.deviceIds) {
      const tempDevice = await this.service.device.findAll({ ids: result.houseInfo.deviceIds });
      device = ctx.helper.convert(tempDevice);
    }
    if (result) {
      await this._getService().update({ views: result.views + 1, id });
      this.success({ ...result, device, advantage });
    } else {
      this.error('获取民宿失败');
    }
  }

  // 获取所有房屋
  async index() {
    const { ctx } = this;
    const { name, address, minRent, maxRent, areaId, status, prop, sort, pageIndex, pageSize } = ctx.params();
    const { createdAt } = ctx.queries;
    const rent = ctx.helper.transformRange([ +minRent || 0, +maxRent || 10000 ]);

    const tempResult = await this._getService().findList({
      name,
      address,
      rent,
      areaId,
      status,
      prop,
      sort,
      pageIndex,
      pageSize,
      createdAt,
      isShowUser: true,
    });
    const result = ctx.helper.flat(tempResult.data);
    if (result) {
      this.success(result, tempResult.count);
    } else {
      this.error('获取民宿失败');
    }
  }

  // 获取登录人的房屋
  async indexMy() {
    const { ctx } = this;
    const { status, prop, sort, pageIndex, pageSize } = ctx.params();
    const { createdAt } = ctx.queries;
    const tempResult = await this._getService().findList({
      status,
      oid: ctx.userId,
      prop,
      sort,
      pageIndex,
      pageSize,
      createdAt,
      isShowUser: true,
    });
    const result = ctx.helper.flat(tempResult.data);
    if (result) {
      this.success(result, tempResult.count);
    } else {
      this.error('获取民宿失败');
    }
  }

  // 获取上架的房屋
  async indexShops() {
    const { ctx } = this;
    const { minRent, maxRent, areaId, prop, sort, pageIndex, pageSize } = ctx.params();
    const { createdAt } = ctx.queries;
    const rent = [ minRent || 0, maxRent || 10000 ];
    if (rent[0] > rent[1]) {
      rent[1] = rent[0] + 1;
    }
    const tempResult = await this._getService().findList({
      rent,
      areaId,
      houseStatus: '4,5',
      houseInfoStatus: 3,
      prop,
      sort,
      pageIndex,
      pageSize,
      createdAt,
    });
    const result = ctx.helper.flat(tempResult.data);
    if (result) {
      this.success(result, tempResult.count);
    } else {
      this.error('获取民宿失败');
    }
  }

  // 获取待审核的房屋
  async indexExamine() {
    const { ctx } = this;
    const { name, address, minRent, maxRent, description, prop, sort, pageIndex, pageSize } = ctx.params();
    const { createdAt, areaId } = ctx.queries;
    const rent = [ minRent || 0, maxRent || 10000 ];
    const tempResult = await this._getService().findList({
      name,
      address,
      rent,
      areaId,
      description,
      status: 1,
      prop,
      sort,
      pageIndex,
      pageSize,
      createdAt,
    });
    const result = ctx.helper.flat(tempResult.data);
    if (result) {
      this.success(result, tempResult.count);
    } else {
      this.error('获取民宿失败');
    }
  }

  async indexViewsRank() {
    const { ctx } = this;
    const tempResult = await this._getService().findList({
      status: 4,
      prop: 'views',
      sort: '0',
      pageSize: 10,
    });
    const result = ctx.helper.flat(tempResult.data);
    if (result) {
      this.success(result, tempResult.count);
    } else {
      this.error('获取民宿失败');
    }
  }

  // 获取登录人所有已上架的房屋
  async allMy() {
    const { ctx } = this;
    const result = await this._getService().findAll({ oid: ctx.userId });
    if (result) {
      this.success(result);
    } else {
      this.error('获取民宿失败');
    }
  }

  async indexAll() {
    const result = await this._getService().findAll({ status: 4 });
    if (result) {
      this.success(result);
    } else {
      this.error('获取民宿失败');
    }
  }

  async statisticalHouse() {
    const { ctx } = this;
    const { startTime } = ctx.params();
    const result = await this._getService().statisticalHouse({ startTime, uid: ctx.userId });
    if (result) {
      this.success(result.map(item => ({ ...item, sum: +item.sum })));
    } else {
      this.error('获取民宿失败');
    }
  }

  async statisticalHouseAll() {
    const { ctx } = this;
    const { startTime } = ctx.params();
    const result = await this._getService().statisticalHouseAll({ startTime });
    if (result) {
      this.success(result.map(item => ({ ...item, sum: +item.sum })));
    } else {
      this.error('获取民宿失败');
    }
  }

  async indexHouseHot() {
    const result = await this._getService().indexHouseHot();
    if (result) {
      this.success(result);
    } else {
      this.error('获取民宿失败');
    }
  }

  async statisticalViews() {
    const { ctx } = this;
    const result = await this._getService().statisticalViews({ uid: ctx.userId });
    if (result) {
      this.success(result.map(item => ({ ...item, value: +item.views })));
    } else {
      this.error('获取民宿失败');
    }
  }

  async statisticalViewsAll() {
    const result = await this._getService().statisticalViewsAll();
    if (result) {
      this.success(result.map(item => ({ ...item, value: +item.views })));
    } else {
      this.error('获取民宿失败');
    }
  }

  async statisticalHouseAdd() {
    const { ctx } = this;
    const { startTime, areaId } = ctx.params();
    const result = await this._getService().statisticalHouseAdd({ startTime, areaId });
    if (result && result[0]) {
      this.success(Object.entries(result[0]).map(item => ({ key: item[0] + '月', value: +item[1] })));
    } else {
      this.error('获取信息失败');
    }
  }

  async indexLike() {
    const { ctx } = this;
    const areaLike = await this.service.collection.collectionAreaLike({ uid: ctx.userId });
    const rentLike = await this.service.collection.collectionRentLike({ uid: ctx.userId });
    const [ firstArea, secondArea ] = [ areaLike[0].areaId, areaLike[1].areaId ];
    let maxRent = 0;
    let secondRent = 0;
    let maxKey = '';
    let secondKey = '';
    for (const key in rentLike[0]) {
      if (+rentLike[0][key] > maxRent) {
        maxKey = key;
        maxRent = +rentLike[0][key];
      }
      if (+rentLike[0][key] < maxRent && +rentLike[0][key] > secondRent) {
        secondKey = key;
        secondRent = +rentLike[0][key];
      }
    }
    const result = await this._getService().indexLike({ firstRent: maxKey.split('-'), secondRent: secondKey.split('-'), firstArea, secondArea });
    if (result && result[0]) {
      this.success(result);
    } else {
      this.error('获取信息失败');
    }
  }
}

module.exports = HouseController;
